package com.jetpackframework.retrofit;

import android.util.Log;

import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;

import com.gwm.annotation.retrofit.HttpModel;
import com.gwm.annotation.room.Dao;
import com.gwm.annotation.router.AutoService;
import com.jetpackframework.Reflector;
import com.jetpackframework.rxjetpack.Observable;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
@AutoService(RetrofitInterface.class)
public class DBDaoInvocationHandler implements RetrofitInterface {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName = method.getName();
        String[] strings = methodName.split("_");
        Dao annotation = method.getDeclaringClass().getAnnotation(Dao.class);
        Object daoInstance = Reflector.on(annotation.value()).method("get" + strings[strings.length - 2]).call();
        Class[] parameters = method.getParameterTypes();
        Class[] parameter = null;
        if (parameters.length > 1){
            parameter = new Class[parameters.length - 1];
            Object[] arg = new Object[args.length -1];
            for (int i = 0 ; i < parameter.length ; i++){
                parameter[i] = parameters[i+1];
                arg[i] = args[i+1];
            }
            Object call = Reflector.with(daoInstance).method(strings[strings.length - 1], parameter).call(arg);
            if (call instanceof LiveData){
                return Observable.liveData((LifecycleOwner) args[0],(LiveData)call);
            }else if (call != null){
                return Observable.just(call);
            }
        }else {
            Object call = Reflector.with(daoInstance).method(strings[strings.length - 1]).call();
            if (call instanceof LiveData){
                Log.e("TAG----",call.toString());
                return Observable.liveData((LifecycleOwner) args[0],(LiveData)call);
            }else if (call != null){
                return Observable.just(call);
            }
        }
        return null;
    }

    @Override
    public Class<?> getAnnotation() {
        return Dao.class;
    }
}
